package com.jcli.novel_p;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.List;
import java.util.Properties;

/**
 *2.0.可视化界面（旧版本
 * 此代码创建了一个包含Swing组件的用户界面，包括文本框、按钮和选项卡窗格。
 * 用户可以在文本框中输入属性（键=值），然后按下“添加属性”按钮来添加属性。
 * 属性将在文本框下方的选项卡中显示。还添加了一个“排序”按钮，用户可以按值对属性进行排序。
 *1.只要打开界面就显示所有键值对，更改后刷新所有键值对，而不是点击排序按钮刷新。在选项卡中的表格显示。
 */
public class WriteToPropertiesSwing {
    private Properties properties;
    private int addedCount = 0;

    public WriteToPropertiesSwing() {
        properties = new Properties();

        try (InputStream inputStream = new FileInputStream("src/main/resources/config.properties")) {
            properties.load(new InputStreamReader(inputStream, "UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 创建Swing界面
        JFrame frame = new JFrame("配置属性编辑器");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 400);
        frame.setLayout(new BorderLayout());

        // 创建文本框和按钮
        JTextArea textArea = new JTextArea(10, 40);
        textArea.setLineWrap(true);
        JScrollPane scrollPane = new JScrollPane(textArea);
        JButton addButton = new JButton("添加属性");

        frame.add(scrollPane, BorderLayout.CENTER);
        frame.add(addButton, BorderLayout.SOUTH);

        // 添加按钮的点击事件监听器
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String input = textArea.getText().trim();
                String[] keyValue = input.split("=");
                if (keyValue.length != 2) {
                    JOptionPane.showMessageDialog(frame, "输入格式无效，请重新输入。", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                String key = keyValue[0];
                String value = keyValue[1];

                if (properties.containsKey(key)) {
                    JOptionPane.showMessageDialog(frame, "键 '" + key + "' 已存在，跳过该项。", "警告", JOptionPane.WARNING_MESSAGE);
                } else if (properties.containsValue(value)) {
                    Set<String> keys = properties.stringPropertyNames();
                    boolean valueExistsWithDifferentKey = false;

                    for (String existingKey : keys) {
                        if (properties.getProperty(existingKey).equals(value) && !existingKey.equals(key)) {
                            valueExistsWithDifferentKey = true;
                            break;
                        }
                    }

                    if (valueExistsWithDifferentKey) {
                        int option = JOptionPane.showConfirmDialog(frame, "值 '" + value + "' 已存在，但键不同。是否录入已有的键值对？", "确认", JOptionPane.YES_NO_OPTION);
                        if (option == JOptionPane.YES_OPTION) {
                            properties.setProperty(key, value);
                            addedCount++;
                            JOptionPane.showMessageDialog(frame, "键 '" + key + "' ='" + value + "' 已录入成功。", "提示", JOptionPane.INFORMATION_MESSAGE);
                        } else {
                            JOptionPane.showMessageDialog(frame, "已跳过键 '" + key + "' 的录入。", "提示", JOptionPane.INFORMATION_MESSAGE);
                        }
                    } else {
                        JOptionPane.showMessageDialog(frame, "值 '" + value + "' 已存在，但键相同，跳过该项。", "警告", JOptionPane.WARNING_MESSAGE);
                    }
                } else {
                    properties.setProperty(key, value);
                    addedCount++;
                    JOptionPane.showMessageDialog(frame, "键 '" + key + "' ='" + value + "' 已录入成功。", "提示", JOptionPane.INFORMATION_MESSAGE);
                }

                // 清空文本框
                textArea.setText("");
            }
        });

        // 显示初始的所有键值对
        JTextArea initialTextArea = new JTextArea(10, 40);
        initialTextArea.setEditable(false);
        initialTextArea.setLineWrap(true);
        JScrollPane initialScrollPane = new JScrollPane(initialTextArea);

        // 显示最终的所有键值对
        JTextArea finalTextArea = new JTextArea(10, 40);
        finalTextArea.setEditable(false);
        finalTextArea.setLineWrap(true);
        JScrollPane finalScrollPane = new JScrollPane(finalTextArea);

        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.addTab("初始键值对", initialScrollPane);
        tabbedPane.addTab("最终键值对", finalScrollPane);

        frame.add(tabbedPane, BorderLayout.EAST);

        // 创建排序按钮
        JButton sortButton = new JButton("排序");
        frame.add(sortButton, BorderLayout.NORTH);

        // 添加排序按钮的点击事件监听器
        sortButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 排序并按照值进行中文多音字排序
                List<Map.Entry<Object, Object>> entryList = new ArrayList<>(properties.entrySet());
                entryList.sort(new PinyinComparator());

                Properties sortedProperties = new Properties();
                for (Map.Entry<Object, Object> entry : entryList) {
                    sortedProperties.setProperty((String) entry.getKey(), (String) entry.getValue());
                }

                // 显示最终的所有键值对
                finalTextArea.setText("");
                for (Object key : sortedProperties.keySet()) {
                    finalTextArea.append(key + "=" + sortedProperties.getProperty((String) key) + "\n");
                }
            }
        });

        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new WriteToPropertiesSwing();
            }
        });
    }

    // 自定义比较器用于按照中文多音字的拼音排序
    static class PinyinComparator implements Comparator<Map.Entry<Object, Object>> {
        private final HanyuPinyinOutputFormat format;

        public PinyinComparator() {
            format = new HanyuPinyinOutputFormat();
            format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
            format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
            format.setVCharType(HanyuPinyinVCharType.WITH_V);
        }

        @Override
        public int compare(Map.Entry<Object, Object> entry1, Map.Entry<Object, Object> entry2) {
            String value1 = (String) entry1.getValue();
            String value2 = (String) entry2.getValue();
            String pinyin1 = getPinyin(value1);
            String pinyin2 = getPinyin(value2);
            return pinyin1.compareTo(pinyin2);
        }

        private String getPinyin(String chinese) {
            StringBuilder pinyin = new StringBuilder();
            for (char c : chinese.toCharArray()) {
                try {
                    String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
                    if (pinyinArray != null && pinyinArray.length > 0) {
                        pinyin.append(pinyinArray[0]);
                    } else {
                        pinyin.append(c);
                    }
                } catch (Exception e) {
                    pinyin.append(c);
                }
            }
            return pinyin.toString();
        }
    }
}
